#!/bin/bash

SSR_URL="https://mewu.xyz/link/krSuzTliy9vv0HgV"
SS_OUTPUT="/opt/web/files/nekom"

function base64_decode() {
    BASE64=$(echo ${1} | sed 's@-@+@g' | sed 's@_@/@g')
    BASE64_CNT=$(( $(echo -n "${BASE64}" | wc -m) ))
    if [[ 0 -eq $(( ${BASE64_CNT} % 4 )) ]]; then
        echo -n "${BASE64}" | base64 -d
    elif [[ 2 -eq $(( ${BASE64_CNT} % 4 )) ]]; then
        echo -n "${BASE64}==" | base64 -d
    elif [[ 3 -eq $(( ${BASE64_CNT} % 4 )) ]]; then
        echo -n "${BASE64}=" | base64 -d
    fi
}

function ssr2fullss() {
    SSR_STRING=${1}
    HOSTNAME=$(echo -n ${SSR_STRING} | awk -F':' '{print $1}')
    PORT=$(echo -n ${SSR_STRING} | awk -F':' '{print $2}')
    PROTO=$(echo -n ${SSR_STRING} | awk -F':' '{print $3}')
    ENCRYPTION=$(echo -n ${SSR_STRING} | awk -F':' '{print $4}')
    CONFUSE=$(echo -n ${SSR_STRING} | awk -F':' '{print $5}')
    PASSWD=$(base64_decode $(echo -n ${SSR_STRING} | awk -F':' '{print $6}' | awk -F'/' '{print $1}') )

    SSR_STRING_PARAM="$(echo -n ${SSR_STRING} | awk -F'?' '{print $2}')"
    SSR_REMARKS=$(base64_decode $(echo -n ${SSR_STRING_PARAM} | sed 's@&@\n@g' | grep -P '^remarks=' | awk -F'=' '{print $2}') )
    SSR_GROUP=$(base64_decode $(echo -n ${SSR_STRING_PARAM} | sed 's@&@\n@g' | grep -P '^group=' | awk -F'=' '{print $2}') )

    SS_CONFIG="${ENCRYPTION}:${PASSWD}@${HOSTNAME}:${PORT}"
    SS_NAME=$(echo -n "${SSR_REMARKS}@${SSR_GROUP}" | tr -d '\n' | xxd -plain -c 10000 | sed 's/\(..\)/%\1/g')
    SS_STRING="ss://$(echo -n ${SS_CONFIG} | base64)#${SS_NAME}"
    echo ${SS_STRING}
}

### Download and preprocess ssr list
for SSR_LINE in $(base64_decode $(curl "${SSR_URL}" 2> /dev/null ) ); do
    STR_DECODE=$(base64_decode $(echo ${SSR_LINE} | sed 's@ssr://@@') )
    ssr2fullss ${STR_DECODE}
done | base64 > ${SS_OUTPUT}
